package com.simtop.controller;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.simtop.common.ServerResponse;
import com.simtop.expection.GlobalException;
import com.simtop.pojo.User;
import com.simtop.pojo.experiment.Experiment;
import com.simtop.pojo.resource.Resources;
import com.simtop.service.ExperimentService;
import com.simtop.service.ResourcesService;
import com.simtop.util.JwtUtil;
import com.simtop.util.convert.Convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvyongwei
 */
@RestController
@RequestMapping("/resources")
@CrossOrigin
public class ResourcesController {

    @Autowired
    private AipContentCensor aipContentCensor;

    @Autowired
    private ResourcesService resourcesService;

    @Autowired
    private ExperimentService experimentService;

    /**
     * 获取用户及内置资源
     *
     * @param request
     * @return
     */
    @PostMapping("/getAllResources")
    public ServerResponse getAllResources(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = resourcesService.selectResources(u.getId());
            return ServerResponse.createBySuccess("获取资源成功", jsonObject);
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg("获取资源失败");
        }
    }

    /**
     * 获取用户资源
     *
     * @param request
     * @return
     */
    @PostMapping("/getSelfResources")
    public ServerResponse getSelfResources(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            List<Resources> selfResources = resourcesService.getSelfResources(u.getId());
            return ServerResponse.createBySuccess("获取资源成功", selfResources);
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg("获取资源失败");
        }
    }

    /**
     * 删除资源
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/deleteResources")
    public ServerResponse deleteResources(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject parse = JSONObject.parseObject(data);
        String ids = parse.getString("ids");
        Long[] arr = Convert.toLongArray(ids);
        try {
            resourcesService.deleteResources(arr);
            return ServerResponse.createBySuccess("删除内容成功");
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg("删除资源失败");
        }
    }

    /**
     * 审核最后提交的富文本中纯文本内容
     *
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/check")
    public ServerResponse add(@RequestBody Experiment experiment, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            experiment.setUserId(u.getId());
            List<String> strings = experimentService.checkExperiment(experiment);
            if (strings == null || strings.size() == 0) {
                return ServerResponse.createByError("审核提交的内容失败", strings.toString());
            }
            return ServerResponse.createBySuccess("审核提交的内容成功", strings.toString());
        } catch (GlobalException e) {
            return ServerResponse.createByError(e.getMsg(), e.getData().toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("审核提交的内容失败");
        }
    }


    /**
     * 根据资源id获取审核结果
     *
     * @param request
     * @return
     */
    @PostMapping("/getResources")
    public ServerResponse getAllResources(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        JSONObject parse = JSONObject.parseObject(data);
        String ids = parse.getString("ids");
        Long[] arr = Convert.toLongArray(ids);
        //拿到所有资源
        List<Resources> resources2 = resourcesService.getResources2(arr);
        for (Resources as : resources2
        ) {
            String type = as.getType();
            Double size = as.getSize();
            if (type.equals("video") && size > 50) {
                //参数认证
                Long id = as.getId();
                String taskid = as.getTaskid();
                String ABC = String.valueOf(aipContentCensor.longVideoCensorPull(taskid, null));
                com.alibaba.fastjson.JSONObject resS = com.alibaba.fastjson.JSONObject.parseObject(ABC);
                System.out.println(ABC);
                if (resS.getString("conclusionq") != null) {
                    String conclusion = resS.getString("conclusion");
                    String conclusionTypeGroupInfos = resS.getString("conclusionTypeGroupInfos");
                    Map<Object, Object> objectObjectMap = new HashMap<>();
                    objectObjectMap.put("conclusion", conclusion);
                    objectObjectMap.put("data", conclusionTypeGroupInfos);
                    Object oS = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMap);
                    //更新审核结果
                    Resources resources = new Resources();
                    resources.setId(id);
                    resources.setCheckResult(oS.toString());
                    boolean b = resourcesService.updateResources(resources);
                } else {
                    Map<Object, Object> objectObjectMapas = new HashMap<>();
                    objectObjectMapas.put("conclusion", "合规");
                    Object oSs = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMapas);
                    //添加审核结果
                    Resources resources = new Resources();
                    resources.setId(id);
                    System.out.println("结果集" + oSs.toString());
                    resources.setCheckResult(oSs.toString());
                    boolean b = resourcesService.updateResources(resources);
                }

            }

            if (type.equals("voice")) {
                //参数认证
                Long id = as.getId();
                String taskid = as.getTaskid();
                String ABC = String.valueOf(aipContentCensor.asyncVoiceCensorPullByTaskId(taskid, null));
                com.alibaba.fastjson.JSONObject resS = com.alibaba.fastjson.JSONObject.parseObject(ABC);
                System.out.println(ABC);
                if (resS.getString("conclusion") != null) {
                    String conclusion = resS.getString("conclusion");
                    if (conclusion.equals("不合规")) {
                        String datas = resS.getString("data");
                        Map<Object, Object> objectObjectMap = new HashMap<>();
                        objectObjectMap.put("conclusion", conclusion);
                        objectObjectMap.put("data", datas);
                        Object oS = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMap);
                        //更新审核结果
                        Resources resources = new Resources();
                        resources.setId(id);
                        resources.setCheckResult(oS.toString());
                        boolean b = resourcesService.updateResources(resources);

                    } if(conclusion.equals("合规")) {
                        Map<Object, Object> objectObjectMapas = new HashMap<>();
                        objectObjectMapas.put("conclusion", "合规");
                        Object oSs = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMapas);
                        //添加审核结果
                        Resources resources = new Resources();
                        resources.setId(id);
                        System.out.println("结果集" + oSs.toString());
                        resources.setCheckResult(oSs.toString());
                        boolean b = resourcesService.updateResources(resources);

                    }
                } else {
                    Map<Object, Object> objectObjectMapas = new HashMap<>();
                    objectObjectMapas.put("conclusion", "合规");
                    Object oSs = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMapas);
                    //添加审核结果
                    Resources resources = new Resources();
                    resources.setId(id);
                    System.out.println("结果集" + oSs.toString());
                    resources.setCheckResult(oSs.toString());
                    boolean b = resourcesService.updateResources(resources);
                }


            }

        }


        try {
            List<Resources> resources = resourcesService.getResources(arr);
            return ServerResponse.createBySuccess("获取资源审核结果成功", resources);
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg("获取资源审核结果失败");
        }
    }
}
